package com.kabuda.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.kabuda.blog.service.LoginService;
import com.kabuda.blog.service.SysUserService;
import com.kabuda.blog.vo.ErrorCode;
import com.kabuda.blog.vo.Result;
import com.kabuda.blog.dao.pojo.SysUser;
import com.kabuda.blog.utils.JWTUtils;
import com.kabuda.blog.vo.params.LoginParams;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author kabuda
 * @create 2023-01-17 10:08
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    //盐值以$1$开头
    public static final String slat = "$1$dabuka";
    //private static final String slat = "mszlu!@###";

    @Override
    public Result login(LoginParams loginParams) {

        String account = loginParams.getAccount();
        String password = loginParams.getPassword();
        //1.检查参数是否为空，为空登录失败
        if(!StringUtils.hasText(account)||!StringUtils.hasText(password)){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        //2.根据参数查询数据库是否存在，不存在登录失败
        //数据库密码使用md5盐值加密了，我们加密再进行比对
        String passwordMD5 = Md5Crypt.md5Crypt(password.getBytes(),slat);
        //String passwordMD5 = DigestUtils.md5Hex(password + slat);
        SysUser sysUser=sysUserService.findUser(account,passwordMD5);
        if(sysUser==null){
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(),ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }

        //3.如果存在，使用jwt生成woken返回给前端
        String token = JWTUtils.createToken(sysUser.getId());

        //4.redis存储token 设置过期时间
        //（获取登录信息时，前端传递过来的token会比对redis里面的token，成功则根据token获取playload信息）
        redisTemplate.opsForValue().set("TOKEN_USER_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);

        return Result.success(token);
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_USER_"+token);
        return Result.success(null);
    }

    @Override
    public SysUser checkToken(String token) {
        //1.token判空
        if(!StringUtils.hasText(token)){
            return null;
        }
        //2.token解析判断
        Map<String, Object> map = JWTUtils.checkToken(token);
        if(map==null){
            return null;
        }
        //3.token存在判断（redis比对）
        String s = redisTemplate.opsForValue().get("TOKEN_USER_" + token);
        if(!StringUtils.hasText(s)){
            return null;

        }
        SysUser sysUser = JSON.parseObject(s, SysUser.class);
        return sysUser;
    }


}
